#include "base.h"


int main(int narg,char **arg)
{
  
  ////////////////////////////////////////
  // Variables 
   ////////////////////////////

	// Usage:
	//./rewrite ft/ft_500 s0ft/s0ft0_s0ft0_0.161229_0500.out s0ft/s0ft1_s0ft0_0.161229_0500.out -Nr=2 -Nmass=5 -Nmom=140

  // Input

  int Nr=2;
  int Nmass=5;
  int Nmom=140;

  for(int i=1; i<narg; i++) {
       if(strncmp(arg[i],"-Nmass",6)==0)  sscanf(arg[i],"-Nmass=%d",&Nmass);
       if(strncmp(arg[i],"-Nr",3)==0)  sscanf(arg[i],"-Nr=%d",&Nr);
       if(strncmp(arg[i],"-Nmom",5)==0)  sscanf(arg[i],"-Nmom=%d",&Nmom);
   }


  check_endianess();
  if (big_endian) printf("ATENTION endianness will be transformed \n");

  
  // read original


  colorcolorspinspin ***FT=(colorcolorspinspin***)malloc(sizeof(colorcolorspinspin)*(Nmass));
  for (int imass=0; imass<Nmass; imass++) FT[imass]=(colorcolorspinspin**)malloc(sizeof(colorcolorspinspin)*(Nr));
  for (int imass=0; imass<Nmass; imass++) for (int ir=0; ir<Nr; ir++)  FT[imass][ir]=(colorcolorspinspin*)malloc(sizeof(colorcolorspinspin)*(Nmom));



  printf("Reading...\n");
  FILE *fin=NULL;
  fin=fopen(arg[1],"rb+");
  if(fin == (FILE *)NULL) {
  fprintf(stderr,"Unable to open file %s for reading\n",arg[1] );
   return EXIT_FAILURE;
  }
   
 for (int ir=0; ir<Nr; ir++) for (int imass=0; imass<Nmass; imass++) for (int imom=0; imom<Nmom; imom++)  
  {
		fread(&FT[imass][ir][imom],sizeof(colorcolorspinspin),1,fin);

		if(big_endian) {
			for (int ic1=0; ic1<3; ic1++) for (int ic2=0; ic2<3; ic2++)  for (int is1=0; is1<4; is1++) for (int is2=0; is2<4; is2++) {
			double FTr=creal(FT[imass][ir][imom][ic1][ic2][is1][is2]);
			double FTi=cimag(FT[imass][ir][imom][ic1][ic2][is1][is2]);
			doubles_to_doubles_changing_endianess(&FTr,&FTr,1);                       
			doubles_to_doubles_changing_endianess(&FTi,&FTi,1);
			FT[imass][ir][imom][ic1][ic2][is1][is2]=FTr+I*FTi;
			}
		}
  }

   fclose(fin);


  // writing in the usual format

  printf("Writing..\n");

  FILE *fout0=NULL;
  FILE *fout1=NULL;
  fout0=fopen(arg[2],"w");
  fout1=fopen(arg[3],"w");

  if(fout1 == (FILE *)NULL) {
     fprintf(stderr,"Unable to open file %s for writing\n",arg[2]);
     return EXIT_FAILURE;
   }
  if(fout0 == (FILE *)NULL) {
    fprintf(stderr,"Unable to open file %s for writing\n",arg[3]);
    return EXIT_FAILURE;
  }

  for (int imass=0; imass<Nmass; imass++) for (int imom=0; imom<Nmom; imom++)  for (int ic1=0; ic1<3; ic1++) for (int ic2=0; ic2<3; ic2++)  for (int is1=0; is1<4; is1++) for (int is2=0; is2<4; is2++)   
  {
	fwrite(&FT[imass][0][imom][ic1][ic2][is1][is2],sizeof(complex),1,fout0);

  }
  for (int imass=0; imass<Nmass; imass++) for (int imom=0; imom<Nmom; imom++)   for (int ic1=0; ic1<3; ic1++) for (int ic2=0; ic2<3; ic2++)  for (int is1=0; is1<4; is1++) for (int is2=0; is2<4; is2++) 
  {
        fwrite(&FT[imass][1][imom][ic1][ic2][is1][is2],sizeof(complex),1,fout1);

  }


   fclose(fout1);
   fclose(fout0);



  return 0;
}
